package com.example.demo.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.example.demo.api.MessageApi;
import com.example.demo.dto.Quote;
import com.example.demo.dto.WeixinMsg;
import com.example.demo.dto.WeixinMsgData;
import com.example.demo.util.OkhttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * @author gsq
 * @date 2025/3/7 15:41
 */
@Slf4j
@Service
public class MsgHandler {

    public static Map<String, String> commandMap = new LinkedHashMap<>(){{
        put("s", "s [股票代码] - 获取股票信息,支持一次查询多只股票(可以是gzmt这样的简写，最多10个) 例如: s 600519 gzmt");
        put("st", "st [股票代码] - 获取股票信息,支持一次查询多只股票(需要完整股票代码，最多10个) 例如: s 600519 000858");
        put("sd", "sd [股票代码] - 获取股票详细信息 例如: sd gzmt");
        put("hp", "hp - 获取命令帮助");
    }};

    public void handler(WeixinMsg weixinMsg) {
        WeixinMsgData data = weixinMsg.getData();
        if (data.getMsgType() != 1L) {
            log.warn("处理消息-暂时处理不了此消息：{}", data.getMsgId());
            return;
        }

        if (!weixinMsg.getAppId().equals(Constants.appId)) {
            log.error("设备Id不匹配！");
            return ;
        }

        WeixinMsgData.Content content = data.getContent();
        String output;
        try {
            output = handler(content.getString());
        } catch (Exception e) {
            output = "出错了，请检查或重试！";
        }
        JSONObject jsonObject = MessageApi.postText(weixinMsg.getAppId(), weixinMsg.getWxid(), output, "");
        log.info("==> 回复消息：{}", jsonObject);
    }

    public String handler(String input) {
        input = input.replaceAll("\\s+", " ");
        String[] cmd = input.split(" ");

        String output = "";
        switch (cmd[0]) {
            case "hp":
                output = getCommandHelp();
                break;
            case "s":
                output = getStockInfo(cmd);
                break;
            case "st":
                output = getStockInfo(cmd);
                break;
            case "sd":
                output = getStockDetailInfo(cmd);
                break;
            default:
                break;
        }
        return output;
    }

    public String getCommandHelp() {
        StringBuilder sb = new StringBuilder();
        Iterator<String> iterator = commandMap.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            sb.append(commandMap.get(key)).append("\n");
        }
        return sb.toString();
    }

    public String getStockInfo(String[] cmd) {
        List<String> list = new ArrayList<>();
        if (Objects.equals(cmd[0], "s")) {
            for (int i = 1; i < cmd.length && i < 11; ++i) {
                JSONArray arr = OkhttpUtil.getXueqiuSuggestJSON(cmd[i]);
                if (arr.isEmpty()) {
                    continue;
                }
                String code = arr.getJSONObject(0).getString("code");
                list.add(code);
            }
        } else {
            list.addAll(Arrays.asList(cmd).subList(1, cmd.length));
        }

        JSONObject jsonObject = OkhttpUtil.getXueqiuBatchJSON(list);
        JSONArray items = jsonObject.getJSONArray("items");
        if (items.isEmpty()) {
            return "未找到股票！";
        }
        StringBuilder sb = new StringBuilder();
        items.forEach(item -> {
            Quote quote = ((JSONObject) item).getObject("quote", Quote.class);
            sb.append(quote.toSummaryString()).append("\n");
        });
        return sb.toString();
    }

    public String getStockDetailInfo(String[] cmd) {
        JSONArray arr = OkhttpUtil.getXueqiuSuggestJSON(cmd[1]);
        if (arr.isEmpty()) {
            return "未找到股票！";
        }
        String code = arr.getJSONObject(0).getString("code");
        JSONObject jsonObject = OkhttpUtil.getXueqiuBatchJSON(List.of(code));
        JSONArray items = jsonObject.getJSONArray("items");
        if (items.isEmpty()) {
            return "未找到股票！";
        }
        Quote quote = items.getJSONObject(0).getObject("quote", Quote.class);
        return quote.toFullString();
    }

}
